package se.mushroomwars.gameplay;

import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Players {

	private List<Player> players;

	public Players() {
		players = Collections.synchronizedList(new ArrayList<Player>());
	}

	public Player find(SocketChannel socket) {
		synchronized (players) {
			Iterator<Player> itr = players.iterator();
			while (itr.hasNext()) {
				Player p = itr.next();
				if (p.getSocket() == socket) {
					return p;
				}
			}
			// assert p != null;
			return null;
		}
	}

	public Player find(String nickName) {
		synchronized (players) {
			Iterator<Player> itr = players.iterator();
			while (itr.hasNext()) {
				Player p = itr.next();
				if (p.getNickName().equals(nickName)) {
					return p;
				}
			}
			// assert p != null;
			return null;
		}
	}
	
	public Player find(int id) {
		synchronized (players) {
			Iterator<Player> itr = players.iterator();
			while (itr.hasNext()) {
				Player p = itr.next();
				if (p.getID() == id) {
					return p;
				}
			}
			// assert p != null;
			return null;
		}
	}

	// set the first player in the list to admin, if no other admin is found
	public void setAdmin() {
		synchronized (players) {
			// make sure there is no other admin
			Iterator<Player> itr = players.iterator();
			while (itr.hasNext()) {
				if (itr.next().isAdmin())
					return;
			}

			itr = players.iterator();
			if (itr.hasNext()) {
				Player p = itr.next();
				p.setAdmin(true);
				System.out.println(p.getNickName() + " is admin!");
			}
		}
	}

	public void add(Player player) {
		assert player != null;
		players.add(player);
	}

	public void remove(Player player) {
		assert player != null;
		players.remove(player);
	}

	public void remove(SocketChannel socket) {
		players.remove(find(socket));
		// players.
	}

	public Iterator<Player> iterator() {
		return players.iterator();
	}

	public void setNickName(SocketChannel socket, String nickName) {
		Player p = find(socket);
		assert p != null;
		p.setNickName(nickName);
	}

	//return a name-list of the connected players
	public ArrayList<String> getLobby() {
		synchronized (players) {
			ArrayList<String> res = new ArrayList<String>();
			Iterator<Player> itr = players.iterator();
			while (itr.hasNext())
				res.add(itr.next().getNickName());
			return res;
		}
	}
}
